package instant.mail.riff;

import java.io.IOException;
import java.io.InputStream;

import android.media.AudioRecord;

/**
 * @author qiangli
 * 
 */
public class AudioRecordInputStream extends InputStream {
	private byte[] buf;
	private int pos;
	private int read;
	private AudioRecord record;
	private int size;

	public AudioRecordInputStream(AudioRecord record, int size) {
		this.record = record;
		this.size = size;
		this.buf = new byte[size];
		//
		this.pos = 0;
		this.read = 0;
	}

	private void _read() {
		pos = 0;
		read = record.read(buf, 0, size);
		switch (read) {
		case AudioRecord.ERROR_INVALID_OPERATION:
			throw new IllegalStateException(
					"read AudioRecord.ERROR_INVALID_OPERATION");
		case AudioRecord.ERROR_BAD_VALUE:
			throw new IllegalStateException("read AudioRecord.ERROR_BAD_VALUE");
		case AudioRecord.ERROR:
			throw new IllegalStateException("read AudioRecord.ERROR");
		default:
			//
		}
	}

	@Override
	public int available() throws IOException {
		if (pos >= read) {
			_read();
			if (read == -1) {
				return 0;
			}
			if (read == 0) {
				return 0;
			}
		}
		return (read - pos);
	}

	@Override
	public boolean markSupported() {
		return false;
	}

	@Override
	public int read() throws IOException {
		throw new RuntimeException("Not supported, use read(byte[])");
	}

	@Override
	public int read(byte[] b) {
		return read(b, 0, b.length);
	}

	/**
	 * Non-blocking read, deviating from the standard API.
	 * may return 0 byte
	 */
	@Override
	public int read(byte[] b, int offset, int length) {
		if (pos >= read) {
			_read();
			if (read == -1) {
				return -1;
			}
			if (read == 0) {
				return 0;
			}
		}
		int cnt = Math.min((read - pos), length);
		for (int i = 0; i < cnt; i++) {
			b[i + offset] = buf[pos + i];
		}
		pos += cnt;
		return cnt;
	}

	@Override
	public void close() throws IOException {
		//
	}
}
